package com.zzyl.nursing.service.impl;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.domain.entity.SysUser;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.common.utils.uuid.IdUtils;
import com.zzyl.framework.config.properties.HuaWeiIotConfigProperties;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IDeviceDataService;
import com.zzyl.nursing.service.IDeviceService;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.ProductVo;
import com.zzyl.system.service.ISysUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * IoT设备管理Service业务层处理
 *
 * @author zjx
 * @date 2025-05-25
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService {
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private IoTDAClient client;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ISysUserService userService;
    @Autowired
    private HuaWeiIotConfigProperties huaWeiIotConfigProperties;

    @Autowired
    private IDeviceDataService deviceDataService;



    /**
     * 查询IoT设备管理
     *
     * @param id IoT设备管理主键
     * @return IoT设备管理
     */
    @Override
    public Device selectDeviceById(Long id) {
        return getById(id);
    }

    /**
     * 查询IoT设备管理列表
     *
     * @param device IoT设备管理
     * @return IoT设备管理
     */
    @Override
    public List<Device> selectDeviceList(Device device) {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 从物联网平台同步产品列表
     *
     * @return
     */
    @Override
    public void getDeviceList() {
        ListProductsResponse response = client.listProducts(new ListProductsRequest());
        if (response == null || response.getHttpStatusCode() != 200) {
            throw new BaseException("从物联网平台查询产品列表失败");
        }
        List<ProductSummary> list = response.getProducts();
        redisTemplate.opsForValue().set(CacheConstants.IOT_PRODUCT_LIST, JSONUtil.toJsonStr(list));
    }

    @Override
    public List<ProductVo> allProduct() {
        String value = redisTemplate.opsForValue().get(CacheConstants.IOT_PRODUCT_LIST);
        if (StringUtils.isBlank(value)) {
            return Collections.emptyList();
        }

        List<ProductSummary> list = JSONUtil.toList(value, ProductSummary.class);


        List<ProductVo> collect = list.stream().map(x -> {
            ProductVo productVo = new ProductVo();
            productVo.setProductKey(x.getProductId());
            productVo.setProductName(x.getName());
            return productVo;
        }).collect(Collectors.toList());
        return collect;
    }

    @Override
    public void register(DeviceDto deviceDto) {

        //1.判断设备名称是否重复
        Long count = this.lambdaQuery().eq(Device::getDeviceName, deviceDto.getDeviceName()).count();
        if (count > 0) {
            throw new BaseException("设备名称已重复");
        }
        //2.判断设备标识是否重复
        //使用雪花算法生成nodeId
        String nodeId = IdUtil.getSnowflakeNextIdStr();
        Long count1 = this.lambdaQuery().eq(Device::getNodeId, nodeId).count();
        if (count > 0) {
            throw new BaseException("设备标识已重复");
        }
        //3.同一位置是否绑定了相同的产品
        Long count2 = this.lambdaQuery().eq(Device::getProductKey, deviceDto.getProductKey())
                .eq(Device::getLocationType, deviceDto.getLocationType())
                .eq(Device::getBindingLocation, deviceDto.getBindingLocation())
                .eq(Device::getPhysicalLocationType, deviceDto.getPhysicalLocationType()).count();
        if (count2 > 0) {
            throw new BaseException("同一位置绑定了相同的产品");
        }
        //4.注册设备
        AddDeviceRequest addDeviceRequest = new AddDeviceRequest();
        AddDevice addDevice = new AddDevice();
        addDevice.setDeviceName(deviceDto.getDeviceName());
        addDevice.setProductId(deviceDto.getProductKey());
        addDevice.setNodeId(nodeId);
        String secret = IdUtils.fastSimpleUUID();
        AuthInfo authInfo = new AuthInfo();
        authInfo.setSecret(secret);
        addDevice.setAuthInfo(authInfo);
        String nickname = deviceDto.getRegisterDeviceRequest().getNickname();
        addDevice.setDescription(nickname);//设备描述信息
        addDeviceRequest.setBody(addDevice);
        AddDeviceResponse response = client.addDevice(addDeviceRequest);
        //注意这个IOT的接口响应201表示创建成功，不是传统的200
        if (response.getHttpStatusCode() != 201) {
            throw new BaseException("注册设备到华为IOT失败");
        }
        //5.保存到数据库中
        Device device = new Device();
        BeanUtils.copyProperties(deviceDto, device);
        device.setSecret(secret);
        String productName = getProductName(deviceDto);
        device.setProductName(productName);
        device.setNickname(nickname);
        device.setIotId(response.getDeviceId());
        device.setDeviceDescription(nickname);
        device.setNodeId(nodeId);
        boolean save = this.save(device);
        if (!save) {
            throw new BaseException("保存设备信息失败");
        }
    }


    private String getProductName(DeviceDto deviceDto) {
        String value = redisTemplate.opsForValue().get(CacheConstants.IOT_PRODUCT_LIST);
        if (StringUtils.isBlank(value)) {
            throw new BaseException("未找到该产品");
        }

        List<ProductSummary> list = JSONUtil.toList(value, ProductSummary.class);
        ProductSummary productSummary = list.stream().filter(x -> x.getProductId().equals(deviceDto.getProductKey())).findFirst().get();
        String productName = productSummary.getName();
        return productName;
    }

    /**
     * 查询设备详情
     *
     * @return
     */
    @Override
    public DeviceDetailVo queryDeviceDetail(String iotId) {
        //1.判断设备是否存在
        if (StringUtils.isBlank(iotId)) {
            throw new BaseException("设备不存在");
        }
        //2.拷贝device到vo中
        DeviceDetailVo vo = new DeviceDetailVo();
        Device device = this.lambdaQuery().eq(Device::getIotId, iotId).one();
        BeanUtils.copyProperties(device, vo);
        //3.补充缺少数据
        SysUser sysUser = userService.selectUserById(Long.valueOf(device.getCreateBy()));
        vo.setCreateBy(String.valueOf(sysUser.getUserId()));
        vo.setCreator(sysUser.getUserName());
        vo.setDeviceSecret(device.getSecret());
        vo.setRegion(huaWeiIotConfigProperties.getRegionId());
        vo.setGmtCreate(device.getCreateTime());
        //4.查询物联网IOT平台中的数据
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.withDeviceId(iotId);
        ShowDeviceResponse response = client.showDevice(request);
        //5.补充数据
        String activeTime = response.getActiveTime();
        if(StringUtils.isNotBlank(activeTime)){
            LocalDateTime localDateTime = OffsetDateTime.parse(activeTime).atZoneSameInstant(ZoneId.of("Asia/Shanghai")).toLocalDateTime();
            vo.setGmtActive(localDateTime);
        }
        if(StringUtils.isNotBlank(response.getFwVersion())) {
            vo.setFirmwareVersion(response.getFwVersion());//固件版本
        }
        vo.setDeviceStatus(response.getStatus());
        vo.setStatus(response.getStatus());

        return vo;
    }


    /**
     * 查看指定产品的已发布物模型中的功能定义详情
     */
    @Override
    public JSONObject queryProductModelInfo(String productKey) {
        ShowProductRequest request = new ShowProductRequest();
        request.withProductId(productKey);
        ShowProductResponse response = client.showProduct(request);
        List<ServiceCapability> serviceCapabilities = response.getServiceCapabilities();
        JSONObject productModelInfo = null;
        if(CollUtil.isNotEmpty(serviceCapabilities)) {
            productModelInfo = JSONUtil.parseObj(serviceCapabilities.get(0));
        }
        return productModelInfo;
    }

    /**
     * 查询指定设备的物模型运行状态
     */
    @Override
    public Map<String, Object> queryDevicePropertyStatus(String deviceName) {
        //1.判断设备是否存在
        if(StringUtils.isBlank(deviceName)){
            throw  new BaseException("设备不存在");
        }
        //2.根据设备名查询设备ID
        Device device = this.lambdaQuery().eq(Device::getDeviceName, deviceName).select(Device::getIotId).one();
        String deviceId = device.getIotId();
        //3.查询物模型的影子数据
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.withDeviceId(deviceId);
        ShowDeviceShadowResponse response = client.showDeviceShadow(request);
        if(response==null || response.getHttpStatusCode()!=200){
            throw new BaseException("查询指定设备的影子数据失败");
        }
        //4.封装数据
        List<DeviceShadowData> shadow = response.getShadow();
        if (shadow == null || shadow.isEmpty()) {
            throw new BaseException("设备影子数据为空");
        }
        DeviceShadowProperties reported = shadow.get(0).getReported();
        String eventTimeStr = reported.getEventTime();
        LocalDateTime eventTime = OffsetDateTime.parse(eventTimeStr, DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmssX")).atZoneSameInstant(ZoneId.of("Asia/Shanghai")).toLocalDateTime();
        Object properties = reported.getProperties();
        JSONObject propert = JSONUtil.parseObj(properties);

        List<Map<String,Object>> list = new ArrayList<>();
        propert.forEach((k,v)->{
            Map<String,Object> map = new HashMap<>();
            map.put("identifier", k);
            map.put("name", v);
            map.put("value", v);
            map.put("time", eventTime);
            list.add(map);
        });
        Map<String,Object> mapper = new HashMap<>();
        mapper.put("propertyStatusInfo", list);
        Map<String,Object> result = new HashMap<>();
        result.put("list", mapper);
        return result;
    }

    @Override
    public void updateNickName(Device device) {
        boolean result = this.updateById(device);
        if(!result){
            throw new BaseException("修改失败");
        }
        UpdateDeviceRequest request = new UpdateDeviceRequest();
        request.withDeviceId(device.getIotId());
        UpdateDevice body = new UpdateDevice();
        body.setDescription(device.getNickname());
        request.withBody(body);
        UpdateDeviceResponse response = client.updateDevice(request);
        if(response.getHttpStatusCode()!=200){
            throw new BaseException("修改设备备注名称失败");
        }
    }

    @Transactional
    @Override
    public void delete(String iotId) {
        Device device = this.lambdaQuery().eq(Device::getIotId, iotId).select(Device::getId).one();
        if(device==null){
            throw new BaseException("该设备不存在");
        }
        boolean result = this.lambdaUpdate().eq(Device::getIotId, iotId).remove();
        if(!result){
            throw new BaseException("删除设备信息失败");
        }
        List<DeviceData> list = deviceDataService.lambdaQuery().eq(DeviceData::getIotId, iotId).list();
        if(CollectionUtil.isNotEmpty(list)){
            deviceDataService.remove(Wrappers.<DeviceData>lambdaQuery().eq(DeviceData::getIotId, iotId));
            DeleteDeviceRequest request = new DeleteDeviceRequest();
            request.withDeviceId(iotId);
            DeleteDeviceResponse respose = client.deleteDevice(request);
            if(respose.getHttpStatusCode()!=200){
                throw new BaseException("删除IoT设备信息失败");
            }
        }
    }


}
